//
//  LMNetworkTools.swift
//  WeiBo
//
//  Created by Li MAc on 2018/11/18.
//  Copyright © 2018 Li MAc. All rights reserved.
//

import UIKit
import AFNetworking

//定义枚举
enum LMWBHTTP{
    case GET
    case POST
}

class LMNetworkTools: AFHTTPSessionManager {

    static let shared : LMNetworkTools = {()->LMNetworkTools in
        //实例化对象
        let instance = LMNetworkTools()
        
        //设置响应反序列化支持的数据类型
        instance.responseSerializer.acceptableContentTypes?.insert("text/plain")
        
        return instance
    }()
    
//    //访问令牌，所有网络请求度基于此令牌
    var accessToken : String? //= "2.002pZ7AH0Ie1bXca05ebb730veEflC"
 //用户ID
    var uid:String? = "496516592"
    //第一次访问时，执行闭包，并且将数据保存在 sharach 常量中
    lazy var  userSG = LMUserSG()
    //专门负责拼接 token 的网络请求方法
    
    var userLogno : Bool {
        return userSG.access_token != nil
    }
    
    func tokenQuset(method: LMWBHTTP = .GET, URLString: String, parameters: [String: AnyObject]?, completed: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->()){
        
        //处理 token 字典
        //1. 判断 参数字典是否存在，如果 为nil 应该新建一个字典
        guard let token = userSG.access_token else{
            completed(nil,false)
            return
        }
        
        
        var par = parameters
        if par == nil {
            //实例化字典
            par = [String : AnyObject]()
        }
        
        par!["access_token"] = token as AnyObject
        //执行下面的函数
        request(URLString: URLString, parameters: par, completed: completed)
    }
    
    //封装GET/POST请求
    //定义默认的是GET
    func request(method: LMWBHTTP = .GET, URLString: String, parameters: [String: AnyObject]?, completed: @escaping (_ json: AnyObject?, _ isSuccess: Bool)->()) {
        
        /*
        get(<#T##URLString: String##String#>, parameters: <#T##Any?#>, progress: <#T##((Progress) -> Void)?##((Progress) -> Void)?##(Progress) -> Void#>, success: <#T##((URLSessionDataTask, Any?) -> Void)?##((URLSessionDataTask, Any?) -> Void)?##(URLSessionDataTask, Any?) -> Void#>, failure: <#T##((URLSessionDataTask?, Error) -> Void)?##((URLSessionDataTask?, Error) -> Void)?##(URLSessionDataTask?, Error) -> Void#>)
 
       */
        /// 定义成功回调闭包
        let success = { (task: URLSessionDataTask,json: Any?)->() in
            completed(json as AnyObject?,true)
        }
        
        /// 定义失败回调闭包
        let failure = {(task: URLSessionDataTask?, error: Error)->() in
            
            if(task?.response as? HTTPURLResponse)?.statusCode == 403{
                print("Token 过期了")
            }
            completed(nil,false)
        }
        
        /// 通过请求方法,执行不同的请求
        // 如果是 GET 请求
        if method == .GET { // GET
            get(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        } else { // POST
            post(URLString, parameters: parameters, progress: nil, success: success, failure: failure)
        }
        
    }

}
